function main(item) {
    const url = item.url;
    
    // 解析URL参数
    const id = ku9.getQuery(url, "id") || "11342412";
    const type = ku9.getQuery(url, "type") || "nojson";
    const cdn = ku9.getQuery(url, "cdn") || "";
    
    try {
        // 获取真实房间号
        const rid = getRealRid(id);
        
        // 获取房间信息
        const roomInfo = getRoomInfo(rid);
        
        if (!roomInfo.isLive) {
            return JSON.stringify({ error: "主播未开播", code: "not_live" });
        }
        
        // 获取UID
        const uid = getUid();
        
        // 获取FLV流
        const flvMap = getFlvStreams(roomInfo.data, uid);
        
        if (!flvMap || Object.keys(flvMap).length === 0) {
            return JSON.stringify({ error: "未找到可用直播流", code: "no_flv_stream" });
        }
        
        // 处理返回结果
        if (type === "json") {
            // 返回所有CDN线路的JSON信息
            const result = {
                roomId: rid,
                roomName: roomInfo.data.roomName || "未知房间",
                anchorName: roomInfo.data.nick || "未知主播",
                liveStatus: roomInfo.isLive,
                streams: flvMap,
                timestamp: Date.now()
            };
            return JSON.stringify({ url: JSON.stringify(result) });
        } else {
            // 返回播放地址
            const playUrl = selectBestStream(flvMap, cdn);
            
            if (!playUrl) {
                return JSON.stringify({ error: "无可用播放地址", code: "no_play_url" });
            }
            
            return JSON.stringify({ url: playUrl });
        }
        
    } catch (e) {
        return JSON.stringify({ error: "系统错误: " + e.message, code: "internal_error" });
    }
}

function selectBestStream(flvMap, preferredCdn) {
    // 如果指定了CDN且存在，优先使用
    if (preferredCdn && flvMap[preferredCdn]) {
        return flvMap[preferredCdn];
    }
    
    // CDN优先级（根据稳定性排序）
    const cdnPriority = ['hscdn', 'alicdn', 'txcdn', 'hwcdn', 'hycdn', 'wscdn'];
    
    // 按优先级选择
    for (const cdnName of cdnPriority) {
        if (flvMap[cdnName]) {
            return flvMap[cdnName];
        }
    }
    
    // 如果优先级CDN都没有，返回第一个
    return Object.values(flvMap)[0];
}

function getRealRid(rid) {
    try {
        const html = ku9.get('https://www.huya.com/' + rid, {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
            'Accept-Language': 'zh-CN,zh;q=0.9'
        });
        
        if (html && html.includes('canonical')) {
            const match = html.match(/<link[^>]*rel="canonical"[^>]*href="https:\/\/www\.huya\.com\/([^"]+)"/i);
            if (match && match[1]) {
                return match[1];
            }
        }
    } catch (e) {
        // 忽略错误，返回原始rid
    }
    return rid;
}

function getRoomInfo(rid) {
    try {
        const roomUrl = 'https://mp.huya.com/cache.php?m=Live&do=profileRoom&roomid=' + rid;
        
        const response = ku9.get(roomUrl, {
            'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.3 Mobile/15E148 Safari/604.1',
            'Accept': 'application/json, text/javascript, */*; q=0.01',
            'Referer': 'https://www.huya.com/'
        });
        
        if (!response) {
            throw new Error('请求失败');
        }
        
        const room = JSON.parse(response);
        
        if (!room) {
            throw new Error('数据解析失败');
        }
        
        if (room.status !== 200 && room.status !== '200') {
            throw new Error('房间状态异常: ' + room.status);
        }
        
        const data = room.data || {};
        const status = data.liveStatus || data.status || data.realLiveStatus || '';
        const isLive = (status === 'ON' || status === 1 || status === '1' || status === 2 || status === '2');
        
        return {
            data: data,
            isLive: isLive
        };
        
    } catch (e) {
        throw new Error('获取房间信息失败: ' + e.message);
    }
}

function getUid() {
    try {
        const payload = JSON.stringify({
            appId: 5002,
            byPass: 3,
            context: '',
            version: '2.4',
            data: {}
        });
        
        const response = ku9.post('https://udblgn.huya.com/web/anonymousLogin', {
            'Content-Type': 'application/json',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'
        }, payload);
        
        if (!response) {
            throw new Error('请求失败');
        }
        
        const result = JSON.parse(response);
        
        if (!result || !result.data || !result.data.uid) {
            throw new Error('UID获取失败');
        }
        
        return result.data.uid.toString();
        
    } catch (e) {
        // 如果获取UID失败，使用随机UID
        return Math.floor(Math.random() * 1000000000000).toString();
    }
}

function getFlvStreams(roomData, uid) {
    const cdnMapSrc = {
        'HY': 'hycdn',
        'AL': 'alicdn',
        'TX': 'txcdn',
        'HW': 'hwcdn',
        'HS': 'hscdn',
        'WS': 'wscdn'
    };
    
    const streams = roomData.stream ? 
        (roomData.stream.baseSteamInfoList || roomData.stream.streamInfoList || []) : [];
    
    const flvMap = {};
    
    for (const stream of streams) {
        if (!stream) continue;
        
        const streamName = stream.sStreamName || '';
        const cdnCode = stream.sCdnType || '';
        const flvUrl = stream.sFlvUrl || '';
        const flvSuffix = stream.sFlvUrlSuffix || 'flv';
        const antiCode = stream.sFlvAntiCode || '';
        
        if (!streamName || !flvUrl) continue;
        
        const cdnName = cdnMapSrc[cdnCode] || cdnCode.toLowerCase();
        const queryString = processAnticode(antiCode, uid, streamName);
        
        let streamUrl = flvUrl.replace(/\/+$/, '') + '/' + streamName + '.' + flvSuffix + '?' + queryString;
        
        // 确保使用HTTPS
        if (streamUrl.startsWith('http://')) {
            streamUrl = 'https://' + streamUrl.substring(7);
        }
        
        flvMap[cdnName] = streamUrl;
    }
    
    return flvMap;
}

function processAnticode(anticode, uid, streamName) {
    if (!anticode) return '';
    
    const params = {};
    const pairs = anticode.split('&');
    
    for (const pair of pairs) {
        const [key, value] = pair.split('=');
        if (key && value !== undefined) {
            params[key] = decodeURIComponent(value);
        }
    }
    
    const f = Math.floor(Date.now() / 100).toString();
    const wsTime = params.wsTime || '';
    
    let fm = params.fm || '';
    if (fm) {
        try {
            const decoded = ku9.decodeBase64(fm);
            if (decoded) {
                fm = decoded.replace(/\$0/g, uid)
                           .replace(/\$1/g, streamName)
                           .replace(/\$2/g, f)
                           .replace(/\$3/g, wsTime);
            }
        } catch (e) {
            fm = '';
        }
    }
    
    const wsSecret = fm ? ku9.md5(fm) : '';
    
    const parts = [
        'wsSecret=' + wsSecret,
        'wsTime=' + wsTime,
        'u=' + uid,
        'seqid=' + f,
        'txyp=' + (params.txyp || ''),
        'fs=' + (params.fs || ''),
        'sphdcdn=' + (params.sphdcdn || ''),
        'sphdDC=' + (params.sphdDC || ''),
        'sphd=' + (params.sphd || ''),
        'exsphd=' + (params.exsphd || ''),
        'ratio=0'
    ];
    
    return parts.join('&');
}